
*This file conducts the estimation with a donut (Table B.5, column 5)

*Bring in regression data
use regression_data_donuts.dta, clear

*drop ROW as an originId
drop if originId==62

egen clusterId=group(originId)

************************************************************************************

*Collapsed version: average across importers
collapse logX_theta* logL* instrument_* se_gyy theta clusterId, by(year sectorId originId)
mkmat se_gyy if originId==1 & year==2010 & sectorId>2, matrix(S)

**************************************************************************************
*Multiple Elasticities: Heterogeneous TE
**************************************************************************************
local indvars c.logL#sectorId
local dvars logX_theta

local instruments c.instrument_1#sectorId

ivreghdfe `dvars'  (`indvars'=`instruments') if sectorId>2 & year==2010, cluster(clusterId) absorb(sectorId#year originId#year) sfirst
*outreg2  using ${tab_dir}/donut.xml, append excel nor2 dec(2)  addstat(F-stat, e(widstat)) noaster nopa
matrix A=e(V)
matrix b=e(b)


*Compute standard errors
keep if year==2010 & sectorId>2
keep originId sectorId theta logX_theta logL instrument_1
sort sectorId

*First step: make matrix of instruments and independent variables, plus the matrix of the derivative of the dependent
*variable with respect to the trade elasticity vector

forvalues x=3/17	{
	gen logX_theta_`x'=-1/theta*logX_theta if sectorId==`x'
	replace logX_theta_`x'=0 if logX_theta_`x'==.
	gen logL_`x'=logL if sectorId==`x'
	replace logL_`x'=0 if logL_`x'==.
	gen instrument_1_`x'=instrument_1 if sectorId==`x'
	replace instrument_1_`x'=0 if instrument_1_`x'==.	
}

*Second step: residualize the logX_theta`x' and logL_`x' with respect to the fixed effects

forvalues x=3/17	{	
	reghdfe logX_theta_`x' if sectorId>2,  ///
	absorb(sectorId originId) res(logX_thetahat_`x') 
	reghdfe logL_`x' if sectorId>2,  ///
	absorb(sectorId originId) res(logLhat_`x') 
	
}

reghdfe logX_theta if sectorId>2,  ///
absorb(sectorId originId) res(y) 


*Third step: construct matrices of instruments and residualized independent and dependent variables
mkmat instrument_1_*, matrix(Z)
mkmat logX_thetahat_*, matrix (Y)
mkmat logLhat_*, matrix(L)
mkmat y, matrix(y)

*Fourth Step: Compute the Jacobian matrices for OLS and IV and the reduced form
matrix J = -inv(Z'*L)*Z'*Y

*Compute the variance-covariance matrix and the standard errors

matrix VD = vecdiag(A+J*diag(S)*diag(S)*J')
mata : st_matrix("SE",  st_matrix("VD"):^(.5))

*Preparing for export
matrix M = b\SE
mata: st_matrix("m2", colshape(st_matrix("M")', 30))

matrix M=m2'
matrix list M

putexcel set table_rhonut, sheet(SE Estimates) modify
putexcel D1=matrix(M)




